package com.mezizy.ifaner;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.mezizy.ifaner.global.Global;
import com.mezizy.ifaner.global.NotScrollableListView;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.Dish;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ConfirmActivity extends ActionBarActivity {
    NotScrollableListView listViewOrderConfirm;
    RadioGroup rdgPayment;
    SimpleAdapter confirmOrderAdapter;
    LinearLayout whereParent;
    View cardViewWhere;
    TextView txtConfirmTotalPrice;
    Spinner spnWhere;

    Map<String, Dish> cart;
    String totalPrice;
    String merchantId;
    String remark = "";
    String deliverPlace = "到餐厅取餐、付款";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confrim);
        getSupportActionBar().hide();

        cart = (Map<String, Dish>) getIntent().getSerializableExtra("cart");
        totalPrice = getIntent().getStringExtra("totalPrice");
        merchantId = getIntent().getStringExtra("merchantId");

        listViewOrderConfirm = (NotScrollableListView) findViewById(R.id.listOrderConfirm);


         spnWhere = (Spinner) findViewById(R.id.spnPlace);
        spnWhere.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (((RadioButton) findViewById(R.id.rdbSpcPlace)).isChecked()) {
                    deliverPlace = (String) spnWhere.getSelectedItem();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        rdgPayment = ((RadioGroup) findViewById(R.id.rdbGroupPayment));
        rdgPayment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                Global.showToast(String.valueOf(checkedId));
                if (whereParent==null&&cardViewWhere.getParent()!=null){
                    whereParent= ((LinearLayout) cardViewWhere.getParent());
                }
                switch (checkedId) {
                    case R.id.rdbSpcPlace:

                        cardViewWhere.setVisibility(View.VISIBLE);
                        whereParent.addView(cardViewWhere,1);
                        spnWhere.setSelection(0);
                        deliverPlace = (String) spnWhere.getItemAtPosition(0);
                        break;
                    case R.id.rdbStore:
                        cardViewWhere.setVisibility(View.INVISIBLE);
                         whereParent.removeView(cardViewWhere);
                        deliverPlace = "到餐厅取餐、付款";
                        break;
                }
            }
        });

        cardViewWhere = findViewById(R.id.cardViewWhere);
        cardViewWhere.setVisibility(View.INVISIBLE);
        whereParent= ((LinearLayout) cardViewWhere.getParent());
        ((LinearLayout) cardViewWhere.getParent()).removeView(cardViewWhere);


        ( findViewById(R.id.cardViewConfirm)).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        ((CardView) v).setCardBackgroundColor(getResources().getColor(R.color.main_orange_darker));

                        break;

                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        ((CardView) v).setCardBackgroundColor(getResources().getColor(R.color.main_orange));
                        break;
                }
                return  false;
            }
        });

        txtConfirmTotalPrice = ((TextView) findViewById(R.id.confirmTotalPrice));
        txtConfirmTotalPrice.setText("NT " + totalPrice);

        confirmOrderAdapter = new SimpleAdapter(this, getData(), R.layout.list_confrim_order, new String[]{"orderName", "orderQuantity", "orderPrice"}, new int[]{R.id.txtConfrimOrderName, R.id.txtConfirmOrderQuantity, R.id.txtConfirmOrderOPrice});

        listViewOrderConfirm.setAdapter(confirmOrderAdapter);

//        Global.showToast(cart.toString());


    }

    @Override
    protected void onStop() {
        super.onStop();
        Global.dismissProgress(ConfirmActivity.this);
    }

    /*
            确认订单，得到一个空白订单号码，然后发送
         */
    public void btnPostOrderClick(View view) {
        final List<Dish> listDish = new ArrayList<>();
        remark = ((EditText) findViewById(R.id.editRemark)).getText().toString();
        for (Iterator<Map.Entry<String, Dish>> iterator = cart.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Dish> next = iterator.next();
            listDish.add(next.getValue());

        }

        final ProgressDialog mProgressDialog = new ProgressDialog(ConfirmActivity.this);
        mProgressDialog.setTitle("提示");
        mProgressDialog.setMessage("正在提交订单");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String newId = Global.getFreeId();
                if (Global.postOrder(newId, merchantId, listDish, remark, deliverPlace)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                            Global.showToast("订单发送成功！");
                            startActivity(new Intent(ConfirmActivity.this, MainActivity.class));
                            finish();


                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                            Global.showToast("网路错误，请检查连线");

                        }
                    });
                }
            }
        }).start();


    }


    public List<Map<String, String>> getData() {
        List<Map<String, String>> list = new ArrayList();

        for (Iterator iterator = cart.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Dish> entry = (Map.Entry<String, Dish>) iterator.next();
            Dish dish = entry.getValue();
            if (dish.getCartQuantity() == 0) {
                continue;
            }
            Map<String, String> map = new HashMap();
            map.put("orderName", dish.getDishesName());
            map.put("orderQuantity", "×" + String.valueOf(dish.getCartQuantity()));
            map.put("orderPrice", String.valueOf(dish.getCartQuantity() * dish.getDishesPrice()));

            list.add(map);
        }

        return list;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_confrim, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
